package com.elastic.test.high_level_client;

import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.sniff.Sniffer;

import java.io.IOException;

/**
 * @author: 李德才
 * @description:
 * @create: 2021-04-11 11:05
 **/
public class HighLevelClient {

    //    获取链接对象
    private static RestClientBuilder restClientBuilder = ClientBuilders.getClientBuilder();
    //    实例化客户端
    private static RestHighLevelClient restHighLevelClient;
    //    嗅探器
    private static Sniffer sniffer;

    public RestHighLevelClient getClient() {
        restHighLevelClient = new RestHighLevelClient(restClientBuilder);
//        十秒刷新一次，更新节点信息
        sniffer = Sniffer.builder(restHighLevelClient.getLowLevelClient()).setSniffAfterFailureDelayMillis(5000).build();
        return restHighLevelClient;
    }


    public void closeRestHighLevelClient() {
        if (restHighLevelClient != null) {
            try {
                sniffer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                restHighLevelClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
